<template>
	<view class="container">

		<view class="form-section">
			<view class="form-group">
				<!-- <view class="form-title">设备信息</view> -->

				<up-form labelPosition="left" :model="deviceInfo" :rules="rules" labelWidth="auto" ref="uForm">
					<view class="section-title">设备信息</view>
					<u-form-item label="设备编号" prop="sbbh" required>
						<up-input v-model="deviceInfo.sbbh" border="bottom" placeholder="请扫描或输入" :disabled="isDisabled"
							@blur="handlesbbhBlur">
							<template #suffix>
								<u-icon name="scan" size="28" @click="scanCode('sbbh')" />
							</template>
						</up-input>
					</u-form-item>

					<u-form-item label="设备名称" prop="deviceInfo.sbmc" required>
						<up-input v-model="deviceInfo.sbmc" border="bottom" placeholder="自动带入" :disabled="true" />
					</u-form-item>
					<u-line margin="20rpx 0 20rpx 0" color="#FDFDFD"></u-line>

					<view class="section-title">故障信息</view>
					<u-form-item label="故障单号" prop="ldbh" required>
						<up-input v-model="deviceInfo.ldbh" border="bottom" placeholder="自动生成" disabled />
					</u-form-item>
					<u-form-item label="录入人员" prop="deviceInfo.lrry" required>
						<up-input v-model="deviceInfo.lrry" border="bottom" disabled placeholder="录入人员" />
					</u-form-item>
					<u-form-item label="录入日期" prop="deviceInfo.lrrq" required>
						<up-input v-model="deviceInfo.lrrq" border="bottom" disabled placeholder="请输入" />
					</u-form-item>

					<u-form-item label="故障时间" prop="faultdate" required>
						<u-datetime-picker ref="datetimePickerRef" v-model="faultDateValue" mode="datetime"
							:show="showFaultDate" @confirm="faultDateConfirm" @cancel="showFaultDate = false" />
						<u-button @click="openFaultDateTimePicker" :disabled="isDisabled">
							{{ deviceInfo.faultdate&&deviceInfo.gzsj ? `${deviceInfo.faultdate} ${deviceInfo.gzsj || ''}` : '请选择时间' }}
						</u-button>
					</u-form-item>

					<!-- <u-form-item label="故障时间" prop="faultdate" class="combined-time-item" required>
					<view class="time-row">

						<view class="time-column">
							<view class="time-label">日期</view>
							<u-datetime-picker ref="datetimePickerRef" v-model="faultDateValue" mode="date"
								:show="showFaultDate" @confirm="faultDateConfirm" @cancel="showFaultDate = false" />
							<u-button @click="showFaultDate = true" :disabled="!isDisabled" class="time-button">
								{{ deviceInfo.faultdate || '请选择日期' }}
							</u-button>
						</view>
						
						<view class="time-column">
							<view class="time-label">时间</view>
							<u-datetime-picker ref="datetimePickerRef" v-model="gzsjValue" mode="time"
								:show="showFaultTime" @confirm="faultTimeConfirm" @cancel="showFaultTime = false" />
							<u-button @click="showFaultTime = true" :disabled="!isDisabled" class="time-button">
								{{ deviceInfo.gzsj || '请选择时间' }}
							</u-button>
						</view>

					</view>
				</u-form-item> -->

					<u-form-item label="故障分类" prop="gzfl" required>
						<u-picker :show="showgzfl" :columns="gzflColumns" @cancel="showgzfl = false"
							@confirm="gzflConfirm" keyName="label">
						</u-picker>
						<u-button @click="showgzfl = true" :disabled="isDisabled">
							{{ deviceInfo.gzfl || '右侧选择' }}</u-button>
					</u-form-item>

					<u-form-item label="故障部位" prop="faultpart" required>
						<up-input :modelValue="deviceInfo.faultpart" border="bottom" placeholder="请输入/右侧选择"
							:disabled="isDisabled" @blur="handlerGZBWInput">
							<template #suffix>
								<u-icon name="arrow-right" size="28" @click="showgzbw = true" v-if="!isDisabled" />
							</template>
						</up-input>
						<popUp :show="showgzbw" :dataList="gzBwDataList" :lineList="gzBwLineList"
							@scrolltolower="gzbwLower" @open="gzbwOpen" @close="this.showgzbw = false"
							@click="gzbwClick" @search="gzSearch">
						</popUp>
					</u-form-item>

					<u-form-item label="故障原因" prop="gzyy" required>
						<u-picker :show="showgzyy" ref="deviceInfo.gzyy" @cancel="showgzyy = false"
							:columns="gzyyColumns" @confirm="gzyyConfirm" keyName="label"></u-picker>
						<u-button @click="showgzyy = true"
							:disabled="isDisabled">{{ deviceInfo.gzyy || '右侧选择' }}</u-button>
					</u-form-item>

					<u-form-item label="故障记录" prop="gznr" class="gznr-textarea" required>
						<view class="textarea-title">
							<text class="textarea-title-text">右侧点击选择</text>
							<u-icon name="arrow-right" size="28" @click="showgzjl = true" v-if="!isDisabled"
								class="title-icon" />
						</view>
						<view class="textarea-container">
							<up-textarea class="textarea-style" v-model="deviceInfo.gznr" placeholder="请输入故障记录"
								autoHeight :disabled="isDisabled" count maxlength="500" :showConfirmBar="false" />
						</view>
						<popUp :show="showgzjl" :dataList="gzjlList" :lineList="gzjlLine" @scrolltolower="gzjlLower"
							@open="gzjlOpen" @close="showgzjl = false" @click="gzjlClick" @search="gzjlSearch"></popUp>
					</u-form-item>

					<!-- <u-form-item prop="gznr" class="gznr-textarea" required>
					<view class="textarea-wrapper">
						<view class="section-subtitle">故障记录</view>
						<view class="textarea-container">
							<up-textarea v-model="deviceInfo.gznr" placeholder="请填写故障记录" count autoHeight
								:disabled="!isDisabled" class="textarea-style" maxlength="500" />
						</view>
					</view>
				</u-form-item> -->

					<!--        非必填项 开始-->
					<view class="toggle-button" v-show="isExpanded">
						<u-form-item label="故障程度" prop="gzcd">
							<u-picker :show="showgzcd" ref="deviceInfo.gzcd" @cancel="showgzcd = false"
								:columns="gzcdColumns" @confirm="gzcdConfirm" keyName="label"></u-picker>
							<u-button @click="showgzcd = true"
								:disabled="isDisabled">{{ deviceInfo.gzcd || '右侧选择' }}</u-button>
						</u-form-item>

						<u-form-item label="维修人员" prop="wxry">
							<up-input :modelValue="deviceInfo.wxry" border="bottom" placeholder="请输入/右侧选择"
								:disabled="isDisabled">
								<template #suffix>
									<u-icon name="arrow-right" size="28" @click="showwzry = true" v-if="!isDisabled" />
								</template>
							</up-input>
							<!-- <popUp :show="showwzry" :dataList="wxryList" :lineList="wxryLine" @scrolltolower="wxryLower"
							@close="this.showwzry = false" @click="wxryClick" @search="wxrySearch">
						</popUp> -->
							<u-picker :show="showwzry" :columns="wxryColumns" @change="wxryChange"
								@confirm="wxryConfirm" @cancel="showwzry = false" keyName="label"></u-picker>
						</u-form-item>

						<!-- <u-form-item label="维修人员" prop="wxry">
						<u-picker :show="showwzry" :columns="wxryColumns" @change="wxryChange" @confirm="wxryConfirm"
							@cancel="showwzry = false" keyName="label"></u-picker>
						<u-button @click="showwzry = true" :disabled="!isDisabled">
							{{ deviceInfo.wxry ? `${deviceInfo.wxbz} - ${deviceInfo.wxry}` : '请输入/右侧选择' }}
						</u-button>
					</u-form-item> -->

						<u-form-item label="维修班组" prop="wxbz">
							<up-input v-model="deviceInfo.wxbz" border="bottom" disabled placeholder="自动带入/输入"
								:disabled="isDisabled" />
						</u-form-item>

						<u-form-item label="操作人员">
							<up-input :modelValue="deviceInfo.czry" border="bottom" placeholder="请输入/右侧选择"
								:disabled="isDisabled">
								<template #suffix>
									<u-icon name="arrow-right" size="28" @click="showczry = true" v-if="!isDisabled" />
								</template>
							</up-input>
							<popUp :show="showczry" :dataList="czryList" :lineList="czryLine" @scrolltolower="czryLower"
								@close="this.showczry = false" @click="czryClick" @search="czrySearch">
							</popUp>
						</u-form-item>

						<u-form-item label="故障类别" prop="faultlevel">
							<up-input v-model="deviceInfo.faultlevel" border="bottom" disabled placeholder="请输入"
								:disabled="isDisabled" />
						</u-form-item>

						<u-form-item label="修复时间" prop="maintdate">
							<u-datetime-picker ref="maintdateRef" v-model="maintDateValue" mode="datetime"
								:show="showMaintDate" @confirm="MaintDateConfirm" @cancel="showMaintDate = false" />
							<u-button @click="openMaintDateTimePicker" :disabled="isDisabled">
								{{ deviceInfo.maintdate&&deviceInfo.xfsj ? `${deviceInfo.maintdate} ${deviceInfo.xfsj || ''}` : '请选择日期时间' }}
							</u-button>
						</u-form-item>

						<u-form-item label="计划停机" prop="deviceInfo.jhtj">
							<up-switch v-model="deviceInfo.jhtj" @change="jhtjChange" :disabled="isDisabled" />
						</u-form-item>

						<u-form-item label="停机台时（小时）" prop="deviceInfo.faultlevel">
							<up-number-box v-model="deviceInfo.tjts" :min="0" :max="100" :step="1" decimal-length="2"
								:disabled="isDisabled" />
						</u-form-item>
					</view>
					<view class="toggle-button" @click="toggleMore">
						<text>{{ isExpanded ? '收起 ▴' : '展开更多 ▾' }}</text>
					</view>

				</up-form>
			</view>

			<view class="action-buttons">
				<u-button class="action-btn confirm-btn" type="primary" size="medium" @click="onConfirm"
					v-show="deviceState === 1 && mode==='details' && this.$userPerssion.sbyPermission(whichworhshop)">
					<u-icon name="checkmark-circle" size="18" color="#fff"></u-icon>
					<text>设备员确认</text>
				</u-button>

				<u-button class="action-btn cancel-confirm-btn" type="warning" size="medium" @click="cancelConfirm"
					v-show="deviceState === 2 && mode==='details' && this.$userPerssion.sbyPermission(whichworhshop)">
					<u-icon name="close-circle" size="18" color="#fff"></u-icon>
					<text>撤销确认</text>
				</u-button>

				<u-button class="action-btn examine-btn" type="success" size="medium" @click="onExamine"
					v-show="deviceState === 2 && mode==='details' && this.$userPerssion.sbkPermission(whichworhshop)">
					<u-icon name="edit-pen" size="18" color="#fff"></u-icon>
					<text>设备科审核</text>
				</u-button>

				<u-button class="action-btn cancel-examine-btn" type="error" size="medium" @click="cancelExamine"
					v-show="deviceState === 3 && mode==='details' && this.$userPerssion.sbkPermission(whichworhshop)">
					<u-icon name="close-circle" size="18" color="#fff"></u-icon>
					<text>撤销审核</text>
				</u-button>
			</view>

			<u-button v-if="!isDisabled&&this.mode=='add' " type="primary" size="large" text="故障提交"
				@click="onSubmit"></u-button>

			<u-button v-if="!isDisabled&&this.mode=='details'&&this.deviceState===1" type="primary" size="large"
				text="保存" @click="onSubmit"></u-button>

		</view>

	</view>
</template>

<script>
	import popUp from "../../../components/popUp/popUp.vue";
	import {
		isBankObj,
		deepClone
	} from '../../../common/commonUnits';
	export default {
		components: {
			popUp
		},
		data() {
			return {
				updateData: {},
				mode: "",
				showgzcd: false,
				showFaultDate: false,
				showFaultTime: false,
				showxfsj: false,
				showgzfl: false,
				showgzbw: false,
				showgzyy: false,
				showwzry: false,
				showgzjl: false,
				showMaintDate: false,
				showczry: false,
				isExpanded: false,

				rules: {
					sbbh: {
						type: 'string',
						message: '请输入设备编号',
						required: true,
						trigger: ['blur', 'change']
					},
					faultdate: {
						type: 'string',
						message: '请选择故障时间',
						required: true,
						trigger: ['blur', 'change']
					},
					gzfl: {
						type: 'string',
						message: '请选择故障分类',
						required: true,
						trigger: ['blur', 'change']
					},
					faultpart: {
						type: 'string',
						message: '请输入/右侧选择故障部位',
						required: true,
						trigger: ['blur', 'change']
					},
					gzyy: {
						type: 'string',
						message: '请选择故障原因',
						required: true,
						trigger: ['blur', 'change']
					},
					gznr: {
						type: 'string',
						message: '请输入/右侧选择故障记录',
						required: true,
						trigger: ['blur', 'change']
					}
				},
				deviceInfo: {
					createtime: this.$commonUnits.FormatTimeOne(new Date(), true, true),
					createuserid: this.$commonUnits.getUserId(),
					czry: '',
					faultdate: '',
					faultlevel: '',
					faultpart: '',
					faulttype: '',
					gzcd: '',
					gzfl: '',
					gznr: '',
					gzsj: '',
					gzyy: '',
					id: '',
					jhtj: false,
					ldbh: '',
					lrrq: this.$commonUnits.FormatTimeOne(new Date(), true, true),
					lrry: this.$commonUnits.getUserId(),
					maintdate: '',
					productionprocess: '',
					rq: '',
					sbbh: '',
					sbid: '',
					sbmc: '',
					sbyqr: '',
					sbyqrtime: '',
					sbysh: '',
					sbyshtime: '',
					tjts: '',
					updatetime: '',
					updateuserid: '',
					wxbz: '',
					wxnr: '',
					wxry: '',
					xfsj: '',
					year: new Date().getFullYear(),
				},
				deviceId: '',
				faultpart: '', //故障部位
				gznr: "",
				// 故障分类相关
				gzfl: '', // 显示用的故障分类名称
				gzflColumns: [
					[]
				], // picker使用的数据结构


				// 故障原因相关
				gzyy: '', // 显示用的故障原因名称
				gzyyColumns: [
					[]
				], // picker使用的数据结构


				// 故障程度相关
				gzcd: '', // 显示用的故障程度名称
				gzcdColumns: [
					[]
				], // picker使用的数据结构


				// 故障部位
				gzBwLineList: [{
					name: '部位名称',
					label: 'equipmentstructure'
				}],
				gzBwDataList: [],

				// 维修人员
				wxryLine: [{
						name: '人员名称',
						label: 'bzry'
					},
					{
						name: '所在班组',
						label: 'bzmc'
					},
				],
				wxryList: [],

				wxryColumns: [
					[],
					[]
				], // 两列数据
				wxryMap: {}, // 班组-人员映射
				currentWxryTeam: '', // 当前选中班组


				// 操作人员
				czryLine: [{
						name: '人员编号',
						label: 'empcode'
					},
					{
						name: '人员名称',
						label: 'empname'
					},
				],
				czryList: [],
				// 故障记录
				gzjlLine: [{
						name: '故障编号',
						label: 'code'
					},
					{
						name: '故障内容',
						label: 'name'
					},
				],
				gzjlList: [],

				gzbwsearchData: {
					equipmentstructure: '',
				},
				gzbwpagination: {
					pageNum: 1, // 当前页码
					pageSize: 20, // 每页条数
					total: 0, // 总条数
				},

				czrysearchData: {
					employeeName: '',
				},
				czrypagination: {
					pageNum: 1, // 当前页码
					pageSize: 20, // 每页条数
					total: 0, // 总条数
				},
				faultDateValue: '',
				maintDateValue: '',
				whichworhshop: "",

			}
		},

		computed: {
			deviceState() {
				const {
					sbyqr,
					sbyqrtime,
					sbysh,
					sbyshtime
				} = this.deviceInfo;

				// 状态1: sbyqr和sbyqrtime都为空
				if ((!sbyqr || sbyqr === '') && (!sbyqrtime || sbyqrtime === '')) {
					return 1;
				}
				// 状态2: sbyqr和sbyqrtime不为空，sbhsh和sbyshtime为空
				else if (sbyqr && sbyqr !== '' && sbyqrtime && sbyqrtime !== '' &&
					(!sbysh || sbysh === '') && (!sbyshtime || sbyshtime === '')) {
					return 2;
				}
				// 状态3: 所有字段都不为空
				else if (sbyqr && sbyqr !== '' && sbyqrtime && sbyqrtime !== '' &&
					sbysh && sbysh !== '' && sbyshtime && sbyshtime !== '') {
					return 3;
				}
				return 0;
			},

			faultDateValue() {
				return this.deviceInfo.faultdate != "" ? new Date(this.deviceInfo.faultdate).getTime() : Date.now();
			},
			maintDateValue() {
				return this.deviceInfo.maintdate != "" ? new Date(this.deviceInfo.maintdate).getTime() : Date.now();
			},
			isDisabled() {
				return this.deviceState != 1 && this.mode === 'details';
			}

		},

		onLoad(e) {
			const {
				mode,
				id,
				whichworhshop
			} = e;
			this.mode = e.mode
			this.whichworhshop = e.whichworhshop
			if (mode === 'add') {
				const timestamp = Date.now(); // 当前时间戳
				this.deviceInfo.lrrq = this.formatTimestamp(timestamp)
				var userInfo = this.$commonUnits.getUserInfo();
				this.deviceInfo.lrry = userInfo.userName;
				this.deviceInfo.czry = userInfo.userName;
				this.deviceInfo.createuserid = this.$commonUnits.getUserId();
				this.deviceInfo.createtime = this.$commonUnits.FormatTimeOne(new Date(), true, true);

				this.deviceInfo.faultdate = this.$commonUnits.FormatTimeOne(new Date(), false, false);
				this.deviceInfo.gzsj = this.formatTime(timestamp);

			} else {
				if (id) {
					this.deviceInfo.id = id;
					this.deviceId = id;
				}
				this.getDeviceData(id);
			}

			// 并行加载所有类型数据
			Promise.all([
				this.getFaultTypeList('GZFL'), //故障分类
				this.getFaultTypeList('GZYY'), //故障原因
				this.getFaultTypeList('GZCD'), //故障程度
				this.getEmployeeList(), //获取操作人员
			]).then(() => {
				if (this.deviceId != null && this.deviceId != '') {
					this.getDeviceData(this.deviceId);
				}
				this.getWxRyDataList(); //维修人员
			}).catch(err => {
				uni.$u.toast('初始化数据加载失败');
			});
		},

		onReady() {
			this.$refs.uForm.setRules(this.rules)
			this.$refs.datetimePickerRef.setFormatter(this.formatter)
		},


		watch: {
			czrysearchData() {
				this.getEmployeeList();
			}
		},

		methods: {
			//初始化
			async getDeviceData(id) {
				try {
					const res = await this.$commonUnits.postRequest(
						"deviceFaultRecord.deviceFaultRecord.getFaultDetail.mobile", {
							id: id
						}
					);
					if (!res.result) {
						this.deviceInfo = {};
						uni.showToast({
							title: '暂无数据',
							icon: 'none'
						});
						return;
					}
					// 数据处理
					const result = res.result;
					result.jhtj = (result.jhtj === "1" || Number(result.jhtj) === 1);
					// 格式化日期
					['faultdate', 'maintdate', 'lrrq'].forEach(field => {
						if (result[field]) {
							result[field] = result[field].slice(0, 10);
						}
					});
					// 使用 $nextTick 确保 Vue 能正确响应数据变化
					this.$nextTick(() => {
						this.deviceInfo = result;
						// 确保设备编号存在后再获取相关数据
						// if (this.deviceInfo.sbbh) {
						// this.getGzBwDataList();
						// }
					});

				} catch (err) {
					this.deviceInfo = {};
					uni.showToast({
						title: '获取数据失败',
						icon: 'none'
					});
				}
			},

			isApproved() { //是否审核
				return this.deviceInfo.sbysh && this.deviceInfo.sbysh != '' &&
					this.deviceInfo.sbyshtime && this.deviceInfo.sbyshtime != '';
			},

			editHandler() {
				if (this.isApproved()) {
					uni.showToast({
						title: '设备员已审核，不允许修改',
						icon: 'none'
					});
					return;
				}

			},
			onConfirm() { //设备员确认
				if (this.$userPerssion.sbyPermission()) {
					let faultRecord = this.$commonUnits.deepClone(this.deviceInfo);
					delete faultRecord.sbbh;
					delete faultRecord.sbmc;
					faultRecord.jhtj = faultRecord.jhtj ? 1 : 0;
					faultRecord.sbyqr = this.$commonUnits.getUserId();
					faultRecord.sbyqrtime = new Date().toISOString().split('T')[0];
					this.$commonUnits.postRequest(
						'deviceFaultRecord.deviceFaultRecord.UpdateFaultRecord.mobile', JSON.stringify({
							faultRecord: faultRecord
						})).then(res => {
						if (res.result) {
							uni.showToast({
								title: '设备员确认成功，即将返回',
								icon: 'none',
								duration: 1000, // 提示显示1秒
								complete: () => {
									setTimeout(() => {
										uni.navigateBack();
									}, 500); // 提示消失后再等0.5秒
								},
							});
						} else {
							uni.showToast({
								title: '设备员确认失败，请重试！',
								icon: 'none'
							});
						}
					});
				} else {
					uni.showToast({
						title: '您没有设备员的权限，请联系管理员配置！',
						icon: 'none'
					});
				}

			},

			cancelConfirm() { //撤销确认
				var userInfo = this.$commonUnits.getUserInfo();
				if (userInfo.userName != this.deviceInfo.sbyqr) {
					uni.showToast({
						title: '非本人确认的数据不可以进行撤销！',
						icon: 'none'
					});
				} else {
					if (this.$userPerssion.sbyPermission()) {
						this.$commonUnits.postRequest(
							'deviceFaultRecord.deviceFaultRecord.cancel.mobile', {
								id: this.deviceInfo.id,
								mode: "1",
							}
						).then(res => {
							if (res.result) {
								uni.showToast({
									title: '取消确认成功，即将返回',
									icon: 'none',
									duration: 1000, // 提示显示1秒
									complete: () => {
										setTimeout(() => {
											uni.navigateBack();
										}, 500); // 提示消失后再等0.5秒
									},
								});
							} else {
								uni.showToast({
									title: '撤销确认失败，请重试！',
									icon: 'none'
								});
							}
						});
					} else {
						uni.showToast({
							title: '您没有设备员的权限，请联系管理员配置！',
							icon: 'none'
						});
					}
				}

			},

			onExamine() { //设备员审核
				if (this.$userPerssion.sbyPermission()) {
					let faultRecord = this.$commonUnits.deepClone(this.deviceInfo);
					delete faultRecord.sbbh;
					delete faultRecord.sbmc;
					faultRecord.jhtj = faultRecord.jhtj ? 1 : 0;
					faultRecord.sbysh = this.$commonUnits.getUserId();
					faultRecord.sbyshtime = new Date().toISOString().split('T')[0];
					this.$commonUnits.postRequest(
						'deviceFaultRecord.deviceFaultRecord.UpdateFaultRecord.mobile', JSON.stringify({
							faultRecord: faultRecord
						})).then(res => {
						if (res.result) {
							uni.showToast({
								title: '设备科审核成功，即将返回',
								icon: 'success',
								duration: 1000, // 提示显示1秒
								complete: () => {
									setTimeout(() => {
										uni.navigateBack();
									}, 500); // 提示消失后再等0.5秒
								},
							});
						} else {
							uni.showToast({
								title: '设备科撤销审核失败，请重试！',
								icon: 'fail'
							});
						}
					});

				} else {
					uni.showToast({
						title: '您没有设备科的权限，请联系管理员配置！',
						icon: 'none'
					});
				}
			},

			cancelExamine() { //撤销审核
				var userInfo = this.$commonUnits.getUserInfo();
				if (userInfo.userName != this.deviceInfo.sbysh) {
					uni.showToast({
						title: '非本人审核的数据不可以进行撤销！',
						icon: 'none'
					});
				} else {
					if (this.$userPerssion.sbyPermission()) {
						this.$commonUnits.postRequest(
							'deviceFaultRecord.deviceFaultRecord.cancel.mobile', {
								id: this.deviceInfo.id,
								mode: "2",
							}
						).then(res => {
							if (res.result) {
								uni.showToast({
									title: '取消审核成功，即将返回',
									icon: 'success',
									duration: 1000, // 提示显示1秒
									complete: () => {
										setTimeout(() => {
											uni.navigateBack();
										}, 500); // 提示消失后再等0.5秒
									},
								});
							} else {
								uni.showToast({
									title: '设备科撤销审核失败，请重试！',
									icon: 'fail'
								});
							}
						});
					} else {
						uni.showToast({
							title: '您没有设备科的权限，请联系管理员配置！',
							icon: 'none'
						});
					}
				}
			},

			//初始化加载故障分类GZFL，原因GZYY，程度GZCD
			async getFaultTypeList(type) {
				try {
					const res = await this.$commonUnits.postRequest(
						"deviceFaultRecord.deviceFaultRecord.getFaultType.mobile", {
							type: type
						}
					);
					if (!res.result || res.result.length === 0) {
						uni.$u.toast(`获取${this.getTypeName(type)}数据不存在，请重试`);
					}
					// 根据不同类型处理数据
					switch (type) {
						case 'GZFL': // 故障分类
							this.gzflColumns = [res.result.map(item => ({
								label: item.gzfl || '',
								value: item.gzfl
							}))];
							break;

						case 'GZYY': // 故障原因
							this.gzyyColumns = [res.result.map(item => ({
								label: item.yyfl || '',
								value: item.yyfl
							}))];
							break;

						case 'GZCD': // 故障程度
							this.gzcdColumns = [res.result.map(item => ({
								label: item.cdfl || '',
								value: item.cdfl
							}))];
							break;
					}

				} catch (err) {
					uni.$u.toast(`获取${this.getTypeName(type)}失败，请重试`);
					// 初始化空数据
					switch (type) {
						case 'GZFL':
							this.gzflColumns = [
								[]
							];
							break;
						case 'GZYY':
							this.gzyyColumns = [
								[]
							];
							break;
						case 'GZCD':
							this.gzcdColumns = [
								[]
							];
							break;
					}
				}
			},

			async getEmployeeList(type) {
				try {
					const currentParams = {
						employeeName: this.czrysearchData.employeeName,
					}
					// 如果搜索条件变化，重置分页
					if (JSON.stringify(currentParams) !== JSON.stringify(this.searchParams)) {
						this.czrypagination.pageNum = 1;
						this.czryList = [];
					}
					this.searchParams = {
						...currentParams
					};
					const params = {
						...currentParams,
						pageNum: this.czrypagination.pageNum,
						pageSize: this.czrypagination.pageSize
					};
					const res = await this.$commonUnits.postRequest(
						"deviceFaultRecord.deviceFaultRecord.getEmployeeList.mobile",
						params
					);
					if (!res.result || res.result.length === 0) {
						uni.$u.toast(`获取人员数据不存在，请重试`);
					}
					// 处理数据
					const newData = res.result.list;
					if (this.czrypagination.pageNum === 1) {
						this.czryList = newData;
					} else {
						this.czryList = [...this.czryList, ...newData];
					}
				} catch (err) {
					uni.$u.toast(`获取人员数据不存在，请重试`);
					// 初始化空数据
					this.czryList = []
				}
			},

			handlesbbhBlur(val) { //设备变化，获取该设备下的故障部位
				this.getsbData(val);
				// this.getGzBwDataList();
			},

			// 辅助方法：获取类型名称
			getTypeName(type) {
				const map = {
					'GZFL': '故障分类',
					'GZYY': '故障原因',
					'GZCD': '故障程度'
				};
				return map[type] || '数据';
			},

			getsbData(id) { //获取设备信息
				this.$commonUnits.postRequest(
					"deviceFaultRecord.deviceFaultRecord.getZcglSbtzByCode.mobile", {
						code: id
					}
				).then(res => {
					if (!res.result || res.result.length === 0) {
						this.deviceInfo.sbid = ''
						this.deviceInfo.sbmc = ''
						uni.showToast({
							title: '输入的设备编号不存在，请重试!',
							icon: 'none'
						});
					} else {
						this.deviceInfo.sbid = res.result[0]["id"]
						this.deviceInfo.sbmc = res.result[0]["sbmc"]
					}
				}).catch(err => {
					uni.showToast({
						title: '输入的设备编号不存在，请重试!',
						icon: 'none'
					});
				});
			},

			getGzBwDataList() { // 获取设备故障部位（前提：选择设备编号）
				// debugger
				if (!(this.$commonUnits.isBankStr(this.deviceInfo.sbbh))) {
					const sblx = this.deviceInfo.sbbh.slice(0, 12)
					this.$commonUnits.postRequest(
						"deviceFaultRecord.deviceFaultRecord.getFaultPart.mobile", {
							equipmentcode: sblx,
							equipmentstructure: this.gzbwsearchData.equipmentstructure
						}
					).then(res => {
						if (!res.result || res.result.length === 0) {
							this.gzBwDataList = [];
							uni.showToast({
								title: '该设备类型下暂无故障部位数据',
								icon: 'none'
							});
						} else {
							this.gzBwDataList = res.result
						}
					}).catch(err => {
						this.gzBwDataList = [];
					});
				} else {
					uni.showToast({
						title: '请先选择设备！',
						icon: 'none'
					});
				}
			},

			async getWxRyDataList() {
				try {
					const res = await this.$commonUnits.postRequest(
						"deviceFaultRecord.deviceFaultRecord.getFaultTeam.mobile"
					);
					if (!res.result || res.result.length === 0) {
						this.wxryList = [];
						uni.showToast({
							title: '获取维修人员失败',
							icon: 'fail'
						});
						return;
					}
					// 重组数据结构
					const teamMap = {};
					res.result.forEach(item => {
						if (!teamMap[item.bzmc]) {
							teamMap[item.bzmc] = [];
						}
						teamMap[item.bzmc].push({
							label: item.bzry,
							value: item.bzry
						});
					});
					this.wxryMap = teamMap;
					this.wxryColumns = [
						Object.keys(teamMap).map(team => ({
							label: team,
							value: team
						})), // 班组列
						teamMap[Object.keys(teamMap)[0]] || [] // 默认第一个班组的人员
					];
				} catch (err) {
					console.error(err);
					this.wxryList = [];
				}
			},

			getGzjlDataList() { //获取故障记录 (前提：选择设备编号 故障部位)
				if (this.deviceInfo.sbbh != null || this.deviceInfo.faultpart != null) {
					const sblx = this.deviceInfo.sbbh.slice(0, 12)
					this.$commonUnits.postRequest(
						"sbyw.SERVICE.getGdxmDatas.mobile", {
							xmmc: "故障内容",
							value: sblx + "," + this.deviceInfo.faultpart,
						}
					).then(res => {
						if (!res.DataObjects || res.DataObjects.length === 0) {
							this.gzjlList = [];
							uni.showToast({
								title: '该设备下故障部位暂无故障记录数据',
								icon: 'none'
							});
						} else {
							this.gzjlList = res.DataObjects
						}
					}).catch(err => {
						this.gzjlList = [];
					});
				} else {
					uni.showToast({
						title: '请先输入设备编号与故障部位！',
						icon: 'none'
					});
				}
			},

			gzflConfirm(e) { // 故障分类确认
				this.handlePickerConfirm(e, 'gzfl', 'gzfl');
			},
			gzyyConfirm(e) { // 故障原因确认
				this.handlePickerConfirm(e, 'gzyy', 'gzyy');
			},
			gzcdConfirm(e) { // 故障程度确认
				this.handlePickerConfirm(e, 'gzcd', 'gzcd');
			},
			handlePickerConfirm(e, displayKey, dataKey) {
				const {
					value
				} = e;
				if (!value || value.length === 0 || value[0].length === 0) { //没有数据
					this[`show${dataKey}`] = false;
					return;
				}
				const selected = value[0];
				// 更新显示值
				this[displayKey] = selected.label;
				this.deviceInfo[dataKey] = selected.value;
				this[`show${dataKey}`] = false;
			},

			scanCode(e) {
				uni.scanCode({
					success: (res) => {
						// 进行查询设备信息,并且填充
						this.deviceInfo.zcglSbtz[e] = res.result
						this.getGzBwDataList();
					}
				});
			},
			// 故障部位 弹窗
			gzbwOpen() {
				//弹窗前获取故障部位信息
				this.getGzBwDataList();
			},
			gzbwLower(e) {},
			gzbwClick(e) {
				this.showgzbw = false;
				this.deviceInfo.faultpart = e.equipmentstructure
				this.faultpart = e.equipmentstructure
			},
			gzSearch(e) {
				this.gzbwsearchData.equipmentstructure = e
				this.getGzBwDataList();
			},
			handlerGZBWInput(e) {
				console.log(e)
				this.deviceInfo.faultpart = e
			},

			// 维修人员 弹窗
			wxryChange(e) {
				const {
					value,
					columnIndex
				} = e;
				// 如果改变了班组列(第0列)
				if (columnIndex === 0) {
					const selectedTeam = value[0].value;
					this.currentWxryTeam = selectedTeam;
					// 更新人员列数据
					this.$set(this.wxryColumns, 1, this.wxryMap[selectedTeam] || []);
				}
			},
			// Picker确认事件
			wxryConfirm(e) {
				const [team, person] = e.value;
				if (team && person) {
					this.deviceInfo.wxbz = team.label; // 班组名称
					this.deviceInfo.wxry = person.label; // 人员名称
				}
				this.showwzry = false;
			},


			// 操作人员 弹窗
			czryLower(e) {
				this.czrypagination.pageNum++;
				this.getEmployeeList();
			},
			czryClick(e) { //操作人员确认点击
				this.showczry = false;
				const name = e.empname;
				let current = this.deviceInfo.czry;
				// 1. 拆分为数组（过滤掉空项）
				let nameList = current ? current.split(',').filter(n => n) : [];
				// 2. 添加新名字
				if (!nameList.includes(name)) {
					nameList.push(name);
				}
				// 3. 拼接为字符串并赋值
				this.deviceInfo.czry = nameList.join(',');
			},
			czrySearch(e) {
				this.czrysearchData.employeeName = e
				this.getEmployeeList();
			},

			// 故障记录 弹窗
			gzjlLower(e) {},
			gzjlClick(e) { //故障记录确认点击
				this.showgzjl = false;
				const name = e.name;
				let current = this.deviceInfo.gznr;
				// 1. 拆分为数组（过滤掉空项）
				let nameList = current ? current.split(',').filter(n => n) : [];
				// 2. 添加新名字
				if (!nameList.includes(name)) {
					nameList.push(name);
				}
				// 3. 拼接为字符串并赋值
				this.deviceInfo.gznr = nameList.join(',');
				this.gznr = nameList.join(',');

			},
			gzjlOpen() {
				this.getGzjlDataList();
			},
			gzjlSearch(e) {},

			jhtjChange(e) {
				if (e === false) {
					this.deviceInfo.tjts = 0
				}
			},

			openFaultDateTimePicker() {
				if (this.isDisabled) return;
				// 如果有现有值，初始化选择器
				if (this.deviceInfo.faultdate && this.deviceInfo.gzsj) {
					const dateStr = this.deviceInfo.faultdate.slice(0, 10);
					const timeStr = this.deviceInfo.gzsj;
					// 拼接成完整的ISO格式字符串
					this.faultDateTime = new Date(`${dateStr} ${timeStr}`).getTime();
				} else {
					// 默认当前时间
					this.faultDateTime = Date.now();
				}
				this.showFaultDate = true;
			},

			faultDateConfirm(e) {
				const selectedDate = new Date(e.value);
				this.faultDateTime = e.value
				// 格式化日期部分 (YYYY-MM-DD)
				const year = selectedDate.getFullYear();
				const month = String(selectedDate.getMonth() + 1).padStart(2, '0');
				const day = String(selectedDate.getDate()).padStart(2, '0');
				const dateStr = `${year}-${month}-${day}`;
				// 格式化时间部分 (HH:mm)
				const hours = String(selectedDate.getHours()).padStart(2, '0');
				const minutes = String(selectedDate.getMinutes()).padStart(2, '0');
				const timeStr = `${hours}:${minutes}`;
				// 赋值到表单
				this.deviceInfo.faultdate = dateStr;
				this.deviceInfo.gzsj = timeStr;
				this.showFaultDate = false;
			},

			openMaintDateTimePicker() {
				if (this.isDisabled) return;
				// 如果有现有值，初始化选择器
				if (this.deviceInfo.maintdate && this.deviceInfo.xfsj) {
					const dateStr = this.deviceInfo.maintdate.slice(0, 10);
					const timeStr = this.deviceInfo.xfsj;
					// 拼接成完整的ISO格式字符串
					this.MaintDateTime = new Date(`${dateStr} ${timeStr}`).getTime();
				} else {
					// 默认当前时间
					this.MaintDateTime = Date.now();
				}
				this.showMaintDate = true;
			},

			MaintDateConfirm(e) {
				const selectedDate = new Date(e.value);
				this.faultDateTime = e.value
				// 格式化日期部分 (YYYY-MM-DD)
				const year = selectedDate.getFullYear();
				const month = String(selectedDate.getMonth() + 1).padStart(2, '0');
				const day = String(selectedDate.getDate()).padStart(2, '0');
				const dateStr = `${year}-${month}-${day}`;
				// 格式化时间部分 (HH:mm)
				const hours = String(selectedDate.getHours()).padStart(2, '0');
				const minutes = String(selectedDate.getMinutes()).padStart(2, '0');
				const timeStr = `${hours}:${minutes}`;
				// 赋值到表单
				this.deviceInfo.maintdate = dateStr;
				this.deviceInfo.xfsj = timeStr;
				this.showMaintDate = false;
			},

			async onSubmit() {
				try {
					// 表单校验
					const valid = await this.$refs.uForm.validate();
					if (!valid) {
						uni.$u.toast('校验失败');
						return;
					}

					const faultRecord = deepClone(this.deviceInfo);
					delete faultRecord.sbbh;
					delete faultRecord.sbmc;
					faultRecord.jhtj = faultRecord.jhtj ? 1 : 0;

					if (this.mode === 'add') {
						// 获取故障单号
						const serialRes = await this.$commonUnits.postRequest(
							"deviceFaultRecord.deviceFaultRecord.getFaultSerialNumber.mobile"
						);
						if (!serialRes.result[0]?.latestSerialNumber) {
							throw new Error('获取故障单号失败')
						}
						faultRecord.ldbh = serialRes.result[0].latestSerialNumber;
						faultRecord.id = this.generate15DigitUUID();
						faultRecord.year = new Date().getFullYear();
						const addRes = await this.$commonUnits.postRequest(
							"deviceFaultRecord.deviceFaultRecord.AddFaultRecord.mobile", JSON
							.stringify({
								faultRecord: faultRecord
							})
						);
						if (addRes) {
							// 显示提示后延迟返回
							uni.showToast({
								title: '操作成功，即将返回',
								icon: 'success',
								duration: 1000, // 提示显示1秒
							});
						}

					} else {

						faultRecord.jhtj = faultRecord.jhtj ? 1 : 0;
						// 修改
						const updateRes = await this.$commonUnits.postRequest(
							"deviceFaultRecord.deviceFaultRecord.UpdateFaultRecord.mobile", JSON
							.stringify({
								faultRecord: faultRecord
							})
						);
						// 结果判断
						if (updateRes) {
							// 显示提示后延迟返回
							uni.showToast({
								title: '操作成功，即将返回',
								icon: 'success',
								duration: 1000, // 提示显示1秒
							});
						}
					}
					//重置表单
					// this.resetForm();

					setTimeout(() => {
						uni.navigateBack();
					}, 1500);
				} catch (err) {

					uni.showToast({
						title: '操作失败，请重试 ',
						icon: 'none'
					});
				}
			},

			resetForm() {
				// 重置主表单数据
				this.deviceInfo = {
					createtime: '',
					createuserid: '',
					czry: '',
					faultdate: '',
					faultlevel: '', //故障类别
					faultpart: '',
					faulttype: '',
					gzcd: '',
					gzfl: '',
					gznr: '',
					gzsj: '',
					gzyy: '',
					id: '',
					jhtj: false,
					ldbh: '',
					lrrq: '',
					lrry: '',
					maintdate: '',
					productionprocess: '',
					rq: '',
					sbbh: '',
					sbid: '',
					sbmc: '',
					sbyqr: '',
					sbyqrtime: '',
					sbysh: '',
					sbyshtime: '',
					tjts: '',
					updatetime: '',
					updateuserid: '',
					wxbz: '',
					wxnr: '',
					wxry: '',
					xfsj: '',
					year: '',
				};

				// 重置表单验证
				this.$refs.uForm.clearValidate();
			},

			formatter(type, value) {
				if (type === 'year') {
					return `${value}年`;
				}
				if (type === 'month') {
					return `${value}月`;
				}
				if (type === 'day') {
					return `${value}日`;
				}
				if (type === 'hour') {
					return `${value}时`;
				}
				if (type === 'minute') {
					return `${value}分`;
				}
				return value;
			},
			timeFormatter(type, value) {
				if (type === 'hour') {
					return `${value}时`;
				}
				if (type === 'minute') {
					return `${value}分`;
				}
				return value;
			},
			toggleMore() { //展示更多
				this.isExpanded = !this.isExpanded;
			},
			formatTimestamp(timestamp) {
				const date = new Date(timestamp);
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				const hours = String(date.getHours()).padStart(2, '0');
				const minutes = String(date.getMinutes()).padStart(2, '0');
				const seconds = String(date.getSeconds()).padStart(2, '0');
				return `${year}-${month}-${day}`;
			},
			// 格式化时间戳为时间字符串 (HH:mm)
			formatTime(timestamp) {
				const date = new Date(timestamp);
				const hours = String(date.getHours()).padStart(2, '0');
				const minutes = String(date.getMinutes()).padStart(2, '0');
				return `${hours}:${minutes}`;
			},
			generate15DigitUUID() {
				let result = '';
				for (let i = 0; i < 32; i++) {
					result += Math.floor(Math.random() * 10); // 0-9随机数
				}
				return result;
			},
		}
	};
</script>
<style>
	.container {
		padding-bottom: 120rpx;
	}

	.form-section {
		padding: 20rpx;
	}

	.form-group {
		background: #ffffff;
		border-radius: 12rpx;
		padding: 24rpx;
		margin-bottom: 20rpx;
	}

	.form-title {
		font-size: 28rpx;
		font-weight: 500;
		color: #333;
		margin-bottom: 20rpx;
		border-left: 4rpx solid #1890ff;
		padding-left: 12rpx;
	}

	.form-item {
		display: flex;
		align-items: center;
		padding: 16rpx 0;
		border-bottom: 1rpx solid #f0f0f0;
	}

	/*展开更多*/
	.toggle-button {
		text-align: center;
		cursor: pointer;
		margin-bottom: 12px;
	}

	.toggle-button text {
		font-size: 14px;
	}

	/* 操作按钮容器 */
	.action-buttons {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(255, 255, 255, 0);
		padding: 20rpx 30rpx;
		z-index: 999;
	}

	/* 基础按钮样式 */
	.action-btn {
		flex: 1;
		min-width: 200rpx;
		height: 80rpx;
		border-radius: 40rpx;
		font-size: 28rpx;
		font-weight: 500;
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
		transition: all 0.3s ease;
	}

	/* 按钮悬停效果 */
	.action-btn:hover {
		transform: translateY(-2rpx);
		box-shadow: 0 6rpx 16rpx rgba(0, 0, 0, 0.15);
	}

	/* 按钮按下效果 */
	.action-btn:active {
		transform: translateY(1rpx);
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
	}

	/* 图标和文字间距 */
	.action-btn u-icon {
		margin-right: 8rpx;
	}

	/* 确认按钮 */
	.confirm-btn {
		background: linear-gradient(135deg, #2979ff, #4a90e2);
		border: none;
	}

	/* 撤销确认按钮 */
	.cancel-confirm-btn {
		background: linear-gradient(135deg, #ff9900, #ffad33);
		border: none;
	}

	/* 审核按钮 */
	.examine-btn {
		background: linear-gradient(135deg, #19be6b, #36cf89);
		border: none;
	}

	/* 撤销审核按钮 */
	.cancel-examine-btn {
		background: linear-gradient(135deg, #fa3534, #ff5c5c);
		border: none;
	}

	/* 响应式调整 */
	@media (max-width: 500px) {
		.action-btn {
			min-width: 45%;
			font-size: 26rpx;
		}
	}

	/* 标题区域 */
	.section-title {
		font-size: 28rpx;
		font-weight: 500;
		color: #333;
		margin-bottom: 20rpx;
		border-left: 4rpx solid #1890ff;
		padding-left: 12rpx;
	}

	.gznr-textarea {}

	.textarea-title {
		display: flex;
		justify-content: space-between;
		align-items: center;
		width: 100%;
		padding: 0 8rpx;
	}

	.title-icon {
		margin-left: auto;
		color: #2979ff;
		margin-right: 30rpx;
		/* 可根据实际效果调整 */
	}

	.textarea-container {
		display: flex;
	}

	/* 文本框样式 */
	.textarea-style {
		width: 100%;
		min-height: 100px;
		font-size: 14px;
		line-height: 1.6;
		padding: 12px;
		box-sizing: border-box;
	}

	::v-deep .u-form-item__body {
		display: flex !important;
		align-items: center !important;
		padding: 16rpx 0 !important;
		border-bottom: 1rpx solid #f0f0f0 !important;
	}

	/* 左侧图标label */
	::v-deep .u-form-item__body__left__content__label {
		min-width: 120rpx !important;
		color: #666 !important;
		font-size: 26rpx !important;
	}

	::v-deep .u-form-item__body__right__content {
		flex: 1 !important;
		color: #333 !important;
		font-size: 26rpx !important;
	}
</style>